package com.kate.mall.order.price;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kate.mall.order.dto.OrderItemDTO;
import com.kate.mall.order.dto.PromotionActivityDTO;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * 多买优惠促销活动价格计算组件
 * @author kate2chan
 *
 */
@Component
public class MultiDiscountPromotionActivityCalculator implements PromotionActivityCalculator {


	/**
	 * 计算促销活动的减免金额
	 */
	@Override
	public PromotionActivityResult calculate(OrderItemDTO item,
											 PromotionActivityDTO promotionActivity) throws Exception {
		BigDecimal totalAmount =  item.getPrice().multiply(new BigDecimal(item.getNumber()));
		Integer purchaseCount = item.getNumber();
		
		String rulesJson = promotionActivity.getRule();
		
		JSONArray rules = JSONUtil.parseArray(rulesJson);
		
		for(int i = 0; i < rules.size(); i++) {
			JSONObject rule = rules.getJSONObject(i);

			Integer thresholdCount = rule.get("thresholdCount",Integer.class);
			Double discountRate = rule.get("discountRate",Double.class);
			
			if(purchaseCount > thresholdCount) {
				return new PromotionActivityResult(totalAmount.multiply (new BigDecimal(1.0 - discountRate)));
			}
		}
		
		return new PromotionActivityResult(); 
	}

}